package com.cjx.auth.service;

import com.cjx.admin.dto.AdminUserDTO;
import com.cjx.admin.dto.AdminUserInfoDTO;
import com.cjx.admin.feign.AdminUserFeign;
import com.cjx.auth.domian.SecurityUser;
import com.cjx.common.api.CommonResult;
import com.cjx.common.api.ResultCode;
import com.cjx.common.constant.MessageConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;


/**
*@Description userdetails服务实现
*@Verson v1.0.0
*@Author cjunxian
*@Date 
*/
@Service
public class UserService implements UserDetailsService {

    @Autowired
    private AdminUserFeign adminUserFeign;

    @Autowired
    private HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        String clientId = request.getParameter("client_id");
        CommonResult result = adminUserFeign.getUserByUsername(username);
        if(ResultCode.USER_NOT_EXIST.getCode() == result.getCode()){
            throw new UsernameNotFoundException(ResultCode.USER_NOT_EXIST.getMessage());
        }

        AdminUserInfoDTO userDTO = (AdminUserInfoDTO) result.getData();
        userDTO.setClientId(clientId);
        SecurityUser user = new SecurityUser(userDTO);

        if (!user.isEnabled()) {
            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        } else if (!user.isAccountNonLocked()) {
            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        } else if (!user.isAccountNonExpired()) {
            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        } else if (!user.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }

        return user;
    }
}
